<?php

namespace App;

use DB;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\IntegralDetail
 *
 * @property int $id
 * @property int $user_id 积分接受者
 * @property int $question_id 题目id（答题）
 * @property int $course_id 课程id(签到)
 * @property string $order_num 订单号（邀请购买）
 * @property string $type 类型:add获得，use使用
 * @property int $integral_num 积分数量
 * @property string $remark 备注
 * @property \Illuminate\Support\Carbon|null $deleted_at
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static bool|null forceDelete()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail newQuery()
 * @method static \Illuminate\Database\Query\Builder|\App\IntegralDetail onlyTrashed()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail query()
 * @method static bool|null restore()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereCourseId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereIntegralNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereOrderNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereQuestionId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereRemark($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\IntegralDetail whereUserId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\IntegralDetail withTrashed()
 * @method static \Illuminate\Database\Query\Builder|\App\IntegralDetail withoutTrashed()
 * @mixin \Eloquent
 */
class IntegralDetail extends Model
{
    use SoftDeletes;

    /**
     * @param $user_id
     * @param int $course_id
     * @param int $question_id
     * @param int $order_id
     * @return int
     */
    public static function addIntegral($user_id,$course_id=0,$question_id=0,$order_id=0){
        $add_integral=0;
        \Log::notice("addIntegral($user_id,$course_id,$question_id,$order_id)");
        try {
            if ($user_id > 0){
                DB::beginTransaction();
                /** @var UserInfo $userInfo */
                $userInfo=UserInfo::whereUserId($user_id)->lockForUpdate()->first();
                if ($userInfo){
                    //签到加积分
                    if ($course_id > 0){
                        $thisCourse = Course::whereId($course_id)->first();
                        if ($thisCourse){
                            /** 查询签到次数 */
                            $signNum=CourseSignRecord::whereUserId($user_id)
                                ->whereCourseId($course_id)
                                ->whereBetween('created_at',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])
                                ->count();
                            if ($thisCourse->check_per_day > 0 && $signNum <= $thisCourse->check_per_day){
                                if ($thisCourse->integral > 0){
                                    $userInfo->integral = $userInfo->integral + $thisCourse->integral;
                                    $userInfo->save();
                                    $record             = new IntegralDetail();
                                    $record->user_id    = $user_id;
                                    $record->course_id  = $course_id;
                                    $record->type       = 'add';
                                    $record->integral_num = $thisCourse->integral;
                                    $record->remark     = '课程签到';
                                    $record->save();
                                    $add_integral=$thisCourse->integral;
                                 }

                            }

                        }
                    }

                    //答题加积分
                    if ($question_id > 0){
                        $thisQuestion = CourseQuestion::whereId($question_id)->first();
                        if ($thisQuestion){

                            /** 查询答题次数 */
//                            $answerNum = CourseQuestionAnswerRecord::whereUserId($user_id)
//                                ->whereCourseQuestionId($question_id)
//                                ->count();
//                            if ($thisQuestion->limit_num > 0 && $answerNum <= $thisQuestion->limit_num){
                                if ($thisQuestion->integral > 0){
//                                    $is_bingo=CourseQuestionAnswerRecord::whereUserId($user_id)
//                                        ->whereCourseQuestionId($question_id)
//                                        ->whereIsBingo(1)
//                                        ->first();
//                                    if ($is_bingo){
                                        $isAnswered         = IntegralDetail::whereUserId($user_id)->whereQuestionId($question_id)->first();
                                        if (!$isAnswered){
                                            $userInfo->integral = $userInfo->integral + $thisQuestion->integral;
                                            $userInfo->save();

                                            $record             = new IntegralDetail();
                                            $record->user_id    = $user_id;
                                            $record->question_id= $question_id;
                                            $record->type       = 'add';
                                            $record->integral_num = $thisQuestion->integral;
                                            $record->remark     = '课程问答';
                                            $record->save();
                                            $add_integral=$thisQuestion->integral;
                                        }

//                                    }

                                }
//                            }

                        }
                    }

                    //邀请下单加积分
                    if ($order_id > 0){
                        $thisOrder = Orders::whereId($order_id)->first();
                        if ($thisOrder){
                            if ($thisOrder->is_pay){
                                $thisItem           = OrderItem::whereOrderId($order_id)->get();
                                if (count($thisItem) > 0){
                                    foreach ($thisItem as $item){
                                        $integral = Course::getShareIntegral($item->course_id);
                                        if ($integral > 0){
                                            $userInfo->integral = $userInfo->integral + $integral;
                                            $record             = new IntegralDetail();
                                            $record->user_id    = $user_id;
                                            $record->order_num  = $thisOrder->order_num;
                                            $record->type       = 'add';
                                            $record->integral_num = $integral;
                                            $record->remark     = '邀请购买';
                                            $record->save();
                                            $add_integral       = $add_integral + $integral;
                                        }
                                    }
                                    $userInfo->save();


                                }


                            }
                        }
                    }
                    DB::commit();
                    return (int)$add_integral;
                }
            }
            return 0;
        } catch (Exception $exception){
            DB::rollBack();
            return $exception->getMessage();
        }
    }

    /**
     * @param $user_id
     * @param $question_id
     * @return int|mixed|string
     * @throws Exception
     */
    public static function addIntegralByAnswer($user_id,$question_id){
        try{
            DB::beginTransaction();
            $userInfo=UserInfo::whereUserId($user_id)->lockForUpdate()->first();
            if ($userInfo){
                //答题加积分
                if ($question_id > 0){
                    $thisQuestion = CourseQuestion::whereId($question_id)->first();
                    if ($thisQuestion){
                        if ($thisQuestion->integral > 0){
                            $isAdd  = IntegralDetail::whereUserId($user_id)->whereQuestionId($question_id)->first();
                            if (!$isAdd){
                                $userInfo->integral = $userInfo->integral + $thisQuestion->integral;
                                $userInfo->save();
                                $record             = new IntegralDetail();
                                $record->user_id    = $user_id;
                                $record->question_id= $question_id;
                                $record->type       = 'add';
                                $record->integral_num = $thisQuestion->integral;
                                $record->remark     = "课程问答：$thisQuestion->question";
                                $record->save();
                                DB::commit();
                                return $record->integral_num;
                            } else {
                                return '0（已获得过）';
                            }
                        } else {
                            return '$thisQuestion->integral !> 0';
                        }
                    } else {
                        return '$thisQuestion';
                    }
                } else {
                    return '$question_id !> 0';
                }
            }
        } catch (Exception $e){
            DB::rollBack();
            return '加积分错误！！';
        }

    }

    public static function addIntegralBySign($user_id,$course_id){
        try{
            DB::beginTransaction();
            /** @var UserInfo $userInfo */
            $userInfo=UserInfo::whereUserId($user_id)->lockForUpdate()->first();
            if ($userInfo){
                //签到
                if ($course_id > 0){
                    $thisCourse = Course::whereId($course_id)->first();
                    if ($thisCourse){
                        /** 查询签到次数 */
                        $signNum=CourseSignRecord::whereUserId($user_id)
                            ->whereCourseId($course_id)
                            ->whereBetween('created_at',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])
                            ->count();
                        if ($thisCourse->check_per_day > 0 && $signNum <= $thisCourse->check_per_day){
                            if ($thisCourse->check_in_integral > 0){
                                if($signNum < 1){
                                    $userInfo->integral = $userInfo->integral + $thisCourse->check_in_integral;
                                    $userInfo->save();
                                }else{
                                    $thisCourse->check_in_integral = 0;
                                }

                                $record             = new IntegralDetail();
                                $record->user_id    = $user_id;
                                $record->course_id  = $course_id;
                                $record->type       = 'add';
                                $record->integral_num = $thisCourse->check_in_integral;
                                $record->remark     = '课程签到';
                                $record->save();
                                DB::commit();
                                return $record->integral_num;
                            } else {
                                return '该课程签到没有积分';
                            }
                        } else {
                            return '签到获积分已达当日上限';
                        }

                    } else {
                        return '!$thisCourse';
                    }
                } else {
                    return '$course_id !> 0';
                }
            } else {
                return '!$userInfo';
            }
        } catch (Exception $e){
            DB::rollBack();
            return '加积分错误！！'.$e->getMessage();
        }
    }

    public static function useIntegral($user_id = 0,$order_num = '',$integral_num = 0){
        /** @var UserInfo $userInfo */
        $userInfo=UserInfo::whereUserId($user_id)->lockForUpdate()->first();
        if ($userInfo && $order_num){
            $record             = new IntegralDetail();
            $record->user_id    = $user_id;
            $record->order_num  = $order_num;
            $record->type       = 'use';
            $record->integral_num = $integral_num ?? 0;
            $record->remark     = '购买课程';
            $record->save();

        }

        return true;
    }
}
